 # coding=utf-8
from django.shortcuts import *
from django.contrib.auth import authenticate, login
from django.template import RequestContext, loader, Context
from django.http import HttpResponse, HttpResponseRedirect
import string
import urllib
import re

import gdata.youtube
import gdata.youtube.service
from gdata.opensearch.data import TotalResults

yt_service = gdata.youtube.service.YouTubeService()

# Turn on HTTPS/SSL access.
# Note: SSL is not available at this time for uploads.
yt_service.ssl = True
yt_service.developer_key = '7gZXDueOwHOqjYXlTYmRRgxDud9DQSORdLrsmfCNascLC30v_nmYTfM8rhoLm37vW3OCHW0ZiimCAwqFwIiplvlLy8BQ'
yt_service.client_id = 'mytube'
def GetVideoID(entry):
    url = entry.id.text
    i = string.find(url, 'videos/') + 7
    return url[i:]
def GetAndPrintVideoFeed(uri):
    feed = yt_service.GetYouTubeVideoFeed(uri)
    for entry in feed.entry:
        PrintEntryDetails(entry)
def PrintEntryDetails(entry):
    print 'Video ID: %s' % GetVideoID(entry)
    print 'Video title: %s' % entry.media.title.text
    print 'Video published on: %s ' % entry.published.text
    print 'Video description: %s' % entry.media.description.text
    print 'Video category: %s' % entry.media.category[0].text
    print 'Video tags: %s' % entry.media.keywords.text
    print 'Video watch page: %s' % entry.media.player.url
    print 'Video flash player URL: %s' % entry.GetSwfUrl()
    print 'Video duration: %s' % entry.media.duration.seconds
    
    # non entry.media attributes
    print 'Video geo location: %s' % entry.geo.location()
    print 'Video view count: %s' % entry.statistics.view_count
    print 'Video rating: %s' % entry.rating.average
    
    # show alternate formats
    for alternate_format in entry.media.content:
        if 'isDefault' not in alternate_format.extension_attributes:
            print 'Alternate format: %s | url: %s ' % (alternate_format.type,
                                                   alternate_format.url)
    
    # show thumbnails
    for thumbnail in entry.media.thumbnail:
        print 'Thumbnail url: %s' % thumbnail.url
            

class PyTube:
    def __init__(self):
        self._formats = {}
        self._formats['13'] = ('3gp', 'Low Quality')
        self._formats['17'] = ('3gp', 'Medium Quality')
        self._formats['36'] = ('3gp', 'Medium Quality')
        self._formats['5'] = ('flv', 'Low Quality')
        self._formats['6'] = ('flv', 'Low Quality')
        self._formats['34'] = ('flv', 'High Quality (320p)')
        self._formats['35'] = ('flv', 'High Quality (480p)')
        self._formats['18'] = ('mp4', 'High Quality (480p)')
        self._formats['22'] = ('mp4', 'High Quality (720p)')
        self._formats['37'] = ('mp4', 'High Quality (1080p)')
    
    def getDownloadLink(self, url):
        videos = []
        html = self._getHTML(url)
#        return html
        if html.find('verify-age-thumb') > -1:
            raise Exception('Adult Video Detected')

        if html.find('das_captcha') > -1:
            raise Exception('Captcha Found please run on a diffrent server')

        matches = re.search(r'url_encoded_fmt_stream_map=(.*?)&', html)
        
        if matches is None:
            raise Exception("Error Locating Downlod URL's")

        formatURL = urllib.unquote_plus(matches.group(1))
        matches = re.search(r'^(.*?)\\\\u0026', formatURL)
        if matches is not None:
            formatURL = matches.group(1)

        urls = formatURL.split(',')
        #url = 'http://' + urls[0][17:]
        url = urls[0][4:]
        i = string.find(url, '&quality');
        url = url[0:i]
        return url
                

    def _getHTML(self, url):
        f = urllib.urlopen(url)
        return f.read()


def watch(request):
    video_id = request.REQUEST.get('id', "")
    if (video_id == ""):
        return HttpResponse('wrong id')
    yt_service = gdata.youtube.service.YouTubeService()
    entry = yt_service.GetYouTubeVideoEntry(video_id = video_id)
    entry.videoid = GetVideoID(entry)
    entry.thumbnail_url = entry.media.thumbnail[0].url
    entry.vd_author = entry.author[0].name.text
    entry.number_view = string.atol(entry.statistics.view_count)
    entry_str = entry.ToString()
    
    i = string.find(entry_str, '<ns1:totalResults>') + 18
    j = string.find(entry_str, '</ns1:totalResults>')
    result_number = entry_str[i:j]     
    related_feed = yt_service.GetYouTubeRelatedVideoFeed(video_id = video_id)
    for one_entry in related_feed.entry:
        one_entry.videoid = GetVideoID(one_entry)
        one_entry.thumbnail_url = one_entry.media.thumbnail[0].url
        one_entry.vd_author = one_entry.author[0].name.text
        one_entry.number_view = string.atol(one_entry.statistics.view_count)
    pytube = PyTube()
    link = pytube.getDownloadLink(entry.media.player.url)
    
    return render_to_response('play_video.html', locals(), context_instance = RequestContext(request))
def index(request):
    yt_service = gdata.youtube.service.YouTubeService()
    featured_feed = yt_service.GetRecentlyFeaturedVideoFeed()
    top_view_feed = yt_service.GetMostViewedVideoFeed()
    top_rate_feed = yt_service.GetTopFavoritesVideoFeed()
    for entry in featured_feed.entry:
        entry.videoid = GetVideoID(entry)
        entry.thumbnail_url = entry.media.thumbnail[0].url
        entry.vd_author = entry.author[0].name.text
        entry.number_view = string.atol(entry.statistics.view_count)
    for entry in top_view_feed.entry:
        entry.videoid = GetVideoID(entry)
        entry.thumbnail_url = entry.media.thumbnail[0].url
        entry.vd_author = entry.author[0].name.text
        entry.number_view = string.atol(entry.statistics.view_count)
        
    for entry in top_rate_feed.entry:
        entry.videoid = GetVideoID(entry)
        entry.thumbnail_url = entry.media.thumbnail[0].url
        entry.vd_author = entry.author[0].name.text
        entry.number_view = string.atol(entry.statistics.view_count)
        entry.favorite_count = string.atol(entry.statistics.favorite_count)

    return render_to_response('default_home.html', locals(), context_instance = RequestContext(request))

def search(request):
    search_query = request.REQUEST.get('search_query', "")
    if search_query == "" :
        return render_to_response('search_results.html', locals(), context_instance = RequestContext(request))
 
    page = request.REQUEST.get('page', "1")
    yt_service = gdata.youtube.service.YouTubeService()
    query = gdata.youtube.service.YouTubeVideoQuery()
    query.vq = search_query
    query.orderby = 'relevance'
    query.racy = 'include'
    query.max_results = 10
    query.start_index = 10 * (string.atoi(page) - 1) + 1
    next_page = string.atoi(page) + 1
    feed = yt_service.YouTubeQuery(query)    
    #return HttpResponse(search_query)
    for entry in feed.entry:
        entry.videoid = GetVideoID(entry)
        entry.thumbnail_url = entry.media.thumbnail[0].url
        entry.vd_author = entry.author[0].name.text
    feed_str = feed.ToString()
    i = string.find(feed_str, '<ns1:totalResults>') + 18
    j = string.find(feed_str, '</ns1:totalResults>')
    result_number = feed_str[i:j]    
    return render_to_response('search_results.html', locals(), context_instance = RequestContext(request))

def GetAndPrintUserUploads(username):
  yt_service = gdata.youtube.service.YouTubeService()
  uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username
  return yt_service.GetYouTubeVideoFeed(uri)
def userplaylist(request):
    username = request.REQUEST.get('id', "vietnamhanoi123")
    yt_service = gdata.youtube.service.YouTubeService()
    uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username
    feed = yt_service.GetYouTubeVideoFeed(uri)
    for entry in feed.entry:
        entry.videoid = GetVideoID(entry)
        entry.thumbnail_url = entry.media.thumbnail[0].url
        entry.vd_author = entry.author[0].name.text
    feed_str = feed.ToString()
    i = string.find(feed_str, '<ns1:totalResults>') + 18
    j = string.find(feed_str, '</ns1:totalResults>')
    result_number = feed_str[i:j]           
    return render_to_response('userpage.html', locals(), context_instance = RequestContext(request))
def download(request):
    url = request.REQUEST.get('url')
    return HttpResponseRedirect(url)
